﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.IBLL.LMS;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.IBLL;
using Apps.Models.LMS;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Data;
using Apps.Models;
using System.Transactions;

namespace Apps.Web.Areas.LMS.Controllers
{
    public class TEMPLATEController : BaseController
    {
        [Dependency]
        public ILMS_TEMPLATE_DETAILBLL m_BLL { get; set; }
        [Dependency]
        public ILMS_TEMPLATEBLL m_TEMPLATEBLL { get; set; }
        [Dependency]
        public ILMS_TEMPLATE_RELATIONBLL m_trBLL { get; set; }
        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList(GridPager pager, string parentId)
        {
            List<V_LMS_TEMPLATEDETAIL> list = m_BLL.GetListDetail(parentId);

            GridRows<V_LMS_TEMPLATEDETAIL> grs = new GridRows<V_LMS_TEMPLATEDETAIL>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }


        [HttpPost]
        public JsonResult GetListDetail(GridPager pager, string parentId,string flag="1")
        {

            List<V_LMS_TEMPLATEDETAIL> list = m_BLL.GetListDetail(parentId,flag=="1"?true:false).Where(a=>!string.IsNullOrEmpty(a.INDEX_ID)).ToList();
            
            GridRows<V_LMS_TEMPLATEDETAIL> grs = new GridRows<V_LMS_TEMPLATEDETAIL>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }
        #region --主表查询--
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetListParent(GridPager pager, string queryStr)
        {
            List<LMS_TEMPLATEModel> list = m_TEMPLATEBLL.GetList(ref pager, queryStr);
            GridRows<LMS_TEMPLATEModel> grs = new GridRows<LMS_TEMPLATEModel>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }

        public void BindData()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(0, "");
            dic.Add(1, "区间值校验");
            dic.Add(2, "基值波动范围");
            SelectList typeList = new SelectList(dic.Select(x => new { Id = x.Key, Name = x.Value }).ToList(), "Id", "Name");
            ViewBag.TypeList = Newtonsoft.Json.JsonConvert.SerializeObject(dic.Select(x => new { Id = x.Key, Name = x.Value }).ToList());


            Dictionary<int, string> dic1 = new Dictionary<int, string>();
            dic1.Add(0, "入厂煤种化验模板");
            dic1.Add(1, "入厂物料化验模板");
            dic1.Add(2, "其他");
            SelectList ttype = new SelectList(dic1.AsEnumerable(), "key", "value",1);
            ViewBag.TTYPE = ttype;

        }
        #endregion        #region 创建
        #region
        [SupportFilter(ActionName = "Create")]
        public ActionResult CreateParent()
        {
            BindData(); 
            return View();
        }

        [HttpPost]
        [SupportFilter(ActionName = "Create")]
        public JsonResult CreateParent(V_LMS_TEMPLATEDETAIL model)
        {
            if (m_TEMPLATEBLL.GetList(ref GridPager.NotPage, model.TEMPLATE_NAME).Count() > 0)
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ",已存在该名称模板"));
            }
            LMS_TEMPLATEModel item = new LMS_TEMPLATEModel();
            item.TEMPLATE_ID = ResultHelper.NewId;
            item.UPDATE_USER = GetUserId();
            item.UPDATE_TIME = ResultHelper.NowTime;
            item.TEMPLATE_NAME = model.TEMPLATE_NAME;
            item.TEMPLATE_TYPE = model.TEMPLATE_TYPE;
            item.TEMPLATE_DESC = model.TEMPLATE_DESC;

            List<V_LMS_TEMPLATEDETAIL> list = JsonConvert.DeserializeObject<List<V_LMS_TEMPLATEDETAIL>>(model.INDEX_NAME);
            List<string> changList = JsonConvert.DeserializeObject<List<string>>(model.INDEX_ID);
            List<LMS_TEMPLATE_DETAIL> details = new List<LMS_TEMPLATE_DETAIL>();
            if (changList.Count > 0)
            {
                for (int i = 0; i < changList.Count; i++)
                {
                    V_LMS_TEMPLATEDETAIL data = list.Where(a => a.INDEX_ID == changList[i]).FirstOrDefault();
                    LMS_TEMPLATE_DETAIL ditem = new LMS_TEMPLATE_DETAIL();
                    ditem.INDEX_ID = data.INDEX_ID;
                    ditem.TEMPLATE_ID = item.TEMPLATE_ID;
                    ditem.VALUE_BASE = data.VALUE_BASE;
                    ditem.VALUE_CHECK = data.VALUE_CHECK == null ? 0 : data.VALUE_CHECK;
                    ditem.VALUE_MAX = data.VALUE_MAX;
                    ditem.VALUE_MIN = data.VALUE_MIN;
                    ditem.VALUE_SHOW = data.VALUE_SHOW == null ? 0 : (decimal)data.VALUE_SHOW;
                    ditem.VALUE_TEST = data.VALUE_TEST == null ? 0 : data.VALUE_TEST;
                    ditem.VALUE_TYPE = data.VALUE_TYPE;
                    details.Add(ditem);
                }
            }
            if (model != null)// && ModelState.IsValid)
            {
                try
                {
                    TransactionOptions transactionOption = new TransactionOptions();
                    //设置事务隔离级别
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                    //设置事务超时时间，这里设置为10分钟
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOption))
                    {

                        if (m_TEMPLATEBLL.Create(ref errors, item))
                        {
                            bool flag = true;
                            if (details.Count > 0)
                            {
                                flag = m_BLL.Creates(ref errors, details);
                            }
                            if (flag)
                            {
                                LogHandler.WriteServiceLog(GetUserId(), "UPDATE_USER" + item.UPDATE_USER + ",UPDATE_TIME" + item.UPDATE_TIME, "成功", "创建", "LMS_TEMPLATE");
                                transactionScope.Complete();
                                return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                            }
                            else
                            {
                                Transaction.Current.Rollback();
                                LogHandler.WriteServiceLog(GetUserId(), "UPDATE_USER" + item.UPDATE_USER + ",UPDATE_TIME" + item.UPDATE_TIME + "," + errors.Error, "失败", "创建", "LMS_TEMPLATE");
                                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + errors.Error));
                            }
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            LogHandler.WriteServiceLog(GetUserId(), "UPDATE_USER" + item.UPDATE_USER + ",UPDATE_TIME" + item.UPDATE_TIME + "," + errors.Error, "失败", "创建", "LMS_TEMPLATE");
                            return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + errors.Error));
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHandler.WriteServiceLog(GetUserId(), ex.Message, "失败", "创建", "LMS_TEMPLATE");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
                }
            }
            else
            {
                LogHandler.WriteServiceLog(GetUserId(), JsonConvert.SerializeObject(ModelState.Values), "失败", "创建", "LMS_TEMPLATE");
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }
        #endregion

        #region 修改
        [SupportFilter(ActionName = "Edit")]
        public ActionResult EditParent(string id)
        {
            V_LMS_TEMPLATEDETAIL entity = m_BLL.GetListDetail(id).FirstOrDefault();
            BindData();
            return View(entity);
        }

        [HttpPost]
        [SupportFilter(ActionName = "Edit")]
        public JsonResult EditParent(V_LMS_TEMPLATEDETAIL model)
        {
            if (model != null)// && ModelState.IsValid)
            {
                LMS_TEMPLATEModel item = new LMS_TEMPLATEModel();
                item.TEMPLATE_ID = model.TEMPLATE_ID;
                item.UPDATE_USER = GetUserId();
                item.UPDATE_TIME = ResultHelper.NowTime;
                item.TEMPLATE_NAME = model.TEMPLATE_NAME;
                item.TEMPLATE_TYPE = model.TEMPLATE_TYPE;
                item.TEMPLATE_DESC = model.TEMPLATE_DESC;

                List<V_LMS_TEMPLATEDETAIL> list = JsonConvert.DeserializeObject<List<V_LMS_TEMPLATEDETAIL>>(model.INDEX_NAME);
                List<string> changList = JsonConvert.DeserializeObject<List<string>>(model.INDEX_ID);
                List<LMS_TEMPLATE_DETAIL> details = new List<LMS_TEMPLATE_DETAIL>();
                if (changList.Count > 0)
                {
                    for (int i = 0; i < changList.Count; i++)
                    {
                        V_LMS_TEMPLATEDETAIL data = list.Where(a => a.INDEX_ID == changList[i]).FirstOrDefault();
                        LMS_TEMPLATE_DETAIL ditem = new LMS_TEMPLATE_DETAIL();
                        ditem.INDEX_ID = data.INDEX_ID;
                        ditem.TEMPLATE_ID = item.TEMPLATE_ID;
                        ditem.VALUE_BASE = data.VALUE_BASE;
                        ditem.VALUE_CHECK = data.VALUE_CHECK == null ? 0: data.VALUE_CHECK;
                        ditem.VALUE_MAX = data.VALUE_MAX;
                        ditem.VALUE_MIN = data.VALUE_MIN;
                        ditem.VALUE_SHOW = data.VALUE_SHOW == null ? 0 : (decimal)data.VALUE_SHOW;
                        ditem.VALUE_TEST = data.VALUE_TEST == null ? 0 : data.VALUE_TEST;
                        ditem.VALUE_TYPE = data.VALUE_TYPE;
                        details.Add(ditem);
                    }
                }
                try
                {
                    TransactionOptions transactionOption = new TransactionOptions();
                    //设置事务隔离级别
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                    //设置事务超时时间，这里设置为8分钟
                    transactionOption.Timeout = new TimeSpan(0, 8, 0);
                    using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOption))
                    {

                        if (m_TEMPLATEBLL.Edit(ref errors, item) || errors.Error == Resource.NoDataChange)
                        {
                            if (m_BLL.GetList(a => a.TEMPLATE_ID == item.TEMPLATE_ID).Count() > 0)
                            {
                                m_BLL.Deletes(ref errors, a => a.TEMPLATE_ID == item.TEMPLATE_ID);
                            }
                            bool flag = true;
                            if (details.Count > 0)
                            {
                                flag = m_BLL.Creates(ref errors, details);
                            }
                            if (flag)
                            {
                                LogHandler.WriteServiceLog(GetUserId(), "UPDATE_USER" + item.UPDATE_USER + ",UPDATE_TIME" + item.UPDATE_TIME, "成功", "修改", "LMS_TEMPLATE");
                                transactionScope.Complete();
                                return Json(JsonHandler.CreateMessage(1, Resource.EditSucceed));
                            }
                            else
                            {
                                Transaction.Current.Rollback();
                                LogHandler.WriteServiceLog(GetUserId(), "UPDATE_USER" + item.UPDATE_USER + ",UPDATE_TIME" + item.UPDATE_TIME + "," + errors.Error, "失败", "修改", "LMS_TEMPLATE");
                                return Json(JsonHandler.CreateMessage(0, Resource.EditFail + errors.Error));
                            }
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            LogHandler.WriteServiceLog(GetUserId(), "UPDATE_USER" + item.UPDATE_USER + ",UPDATE_TIME" + item.UPDATE_TIME + "," + errors.Error, "失败", "修改", "LMS_TEMPLATE");
                            return Json(JsonHandler.CreateMessage(0, Resource.EditFail + errors.Error));
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHandler.WriteServiceLog(GetUserId(), ex.Message, "失败", "创建", "LMS_TEMPLATE");
                    return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
                }
            }
            else
            {
                LogHandler.WriteServiceLog(GetUserId(), JsonConvert.SerializeObject(ModelState.Values), "失败", "创建", "LMS_TEMPLATE");
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }
        #endregion

        #region 详细
        [SupportFilter(ActionName = "Details")]
        public ActionResult DetailsParent(string id)
        {
            LMS_TEMPLATEModel entity = m_TEMPLATEBLL.GetById(id);
            return View(entity);
        }

        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter(ActionName = "Delete")]
        public ActionResult DeleteParent(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                try
                {
                    if (m_trBLL.GetList(ref GridPager.NotPage, id).Count() > 0)
                    {
                        return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + "该模板正在使用中,无法删除"));
                    }
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        m_BLL.Deletes(ref errors, a => a.TEMPLATE_ID == id);
                            m_trBLL.Deletes(ref errors, a => a.TEMPLATE_ID == id);
                        if ( m_TEMPLATEBLL.Delete(ref errors, id))
                        {
                            LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + id, "成功", "删除", "LMS_TEMPLATE");
                            transactionScope.Complete();
                            return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + id + "," + errors.Error, "失败", "删除", "LMS_TEMPLATE");
                            return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + errors.Error));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Transaction.Current.Rollback();
                    LogHandler.WriteServiceLog(GetUserId(), "TEMPLATE_ID" + id + "," + errors.Error, "失败", "创建", "LMS_TEMPLATE");
                    return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + errors.Error));

                }

            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
    }
}

